<template>
  <div class="container">
    <div class="content-body" v-show="loading.init">
      <img class="notwork-icon" src="@/assets/images/not-network.png" alt=""/>
      <p class="hint">{{ hint }}</p>
      <div
        class="button"
        @click="getData(() => { loading.request = false })">
        <span v-show="!loading.request">重新加载</span>
        <img
          v-show="loading.request"
          class="loading-icon"
          src="@/assets/images/circle-loading.png"
          alt=""
        />
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
  import { reactive } from 'vue';
  import { BaseReloadingType } from './type';

  const props = withDefaults(defineProps<BaseReloadingType>(),{
    requestMethod: () => {},
    hint: '数据加载失败，请检查网络',
    promise: true,
    onSuccess: () => {}
  });

  const loading = reactive({
    init: false,
    request: false
  });

  const getData = async (callback: Function) => {
    let res: any = null;
    loading.request = true;
    try {
      props.promise ? res = await props.requestMethod() : await new Promise((resolve) => {
        setTimeout(() => {
          resolve((res = props.requestMethod()));
        }, 300);
      });
      res && props.onSuccess(res);
    } catch (e) {
      console.error(e);
    } finally {
      callback && callback(res);
    }
  }

  (() => {
    getData(() => {
      loading.init = true;
      loading.request = false;
    });
  })();

</script>

<style scoped lang="scss">
  @mixin fontStyle($size) {
    font-size: #{ $size }rem;
    font-family: xiaolai;
    color: red;
  }

  @keyframes circleRote {
    0% {
      transform: rotate(0deg);
    }
    100% {
      transform: rotate(360deg);
    }
  }

  .container {
    position: fixed;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    background-color: #fff;
    z-index: 99;

    .content-body {
      height: 100%;
      width: 100%;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
    }

    .notwork-icon {
      width: 10rem;
      height: auto;
    }

    .hint {
      @include fontStyle(1.7);
      margin-top: 3rem;
      margin-bottom: 3rem;
    }

    .button {
      @include fontStyle(1.7);
      height: 4rem;
      display: flex;
      align-items: center;
      justify-content: center;
      width: 10rem;
      border: 2px solid #FFFFFF;
      background-color: #C5CE73;
      border-radius: 1rem;
      box-sizing: border-box;

      .loading-icon {
        height: 2rem;
        width: 2rem;
        animation: circleRote 1s linear infinite;
      }
    }
  }
</style>